// Appetizor.js
// Contains Backbone.js models, views, controllers

var Appetizor = {
	backbone : {}
}

Appetizor.backbone.Dish = Backbone.Model.extend({

});

Appetizor.backbone.DishCollection = Backbone.Collection.extend({
	model: Appetizor.backbone.Dish,
	
	// removeAll: function() {
		// this.each(function (m) { m.marker.setMap(null); });
		// this.models.splice(0, this.models.length);
		
	// },

    // comparator: function (dish) {
      // return dish.get('order');
    // }

});

Appetizor.backbone.MainView = Backbone.View.extend({
	el: $("#dish-list"),
	
	initialize: function() {
		_.bindAll(this, 'addDish', 'onDishTileHover', 'onDishTileClick', 'callBack',
			'toggleFilterPanel');
		
		// collection of google map markers
		this.markers = {};	
		
		// keep track of which dish detail view is being displayed
		this.activeDishId = -1;
		
		// the model is a collection of dishes
		this.model.each(this.addDish);
		
		// prevent event propagation on links
		$("a").bind("click", function(e) { e.stopPropagation(); });
		
		//
		$("#filter-btn").click(this.toggleFilterPanel);
	},
	
	addDish: function(dish, index) {		
		// create subviews
		var listView = new Appetizor.backbone.DishListView({model: dish});
		
		var detailsView = new Appetizor.backbone.DishDetailsView({model: dish});
		
		if (Appetizor.map != null)
		{
			var mapView = new Appetizor.backbone.DishMapView({model: dish, markers: this.markers});
			dish.mapView = mapView;
		}
		
		dish.listView = listView;
		dish.detailsView = detailsView;

		
		// subscribe to events
		listView.addMouseEnterListener(this.onDishTileHover);
		listView.addMouseLeaveListener(this.onDishTileLeave);
		listView.addClickListener(this.onDishTileClick);
				
		// render them
		$("#dish-list").append(listView.render().el);

	},
	
	toggleFilterPanel: function() {
		$('#filter-panel').animate({ 'height': 'toggle' });
		
	},
	
	onDishTileHover: function(dish) {
		if (dish.mapView != null)
		{
			dish.mapView.activateMarker();
		}
	},
	
	onDishTileLeave: function(dish) {
		if (dish.mapView != null)
		{
			dish.mapView.deactivateMarker();
		}
	},
	
	onDishTileClick : function(dish) {
		$("#panel-content").html(dish.detailsView.render().el)
		$("#panel-content").children().hide();
		var isActive = dish.get('pk') == this.activeDishId;

		if ($('#slideout-panel').css('display')=='none') {
			$('#slideout-panel').animate({ width: 'show' }, 200,  function () {
				$("#panel-content").children().fadeIn();
			});
		}
		else {					
			if (isActive) {
				$("#panel-content").children().hide();
				$('#slideout-panel').animate({
					width: 'hide',
				}, 200);
			}
			else {
				$("#panel-content").children().fadeIn();
			}
		}
			
			
		//$("#slideout-panel").slideToggle(dish.get('pk') == this.activeDishId, this.callBack);
		
		if ($("#slideout-panel").css('display') == 'none')
			this.activeDishId = -1;
		else {
			this.activeDishId = dish.get('pk');

		}
		
		// slideout if necessary
		
	},
})

Appetizor.backbone.DishMapView = Backbone.View.extend({
	events: {
		"mouseenter" : "onMarkerHover",
		"mouseleave" : "onMarkerLeave",
	},

    initialize: function (options) {
		_.bindAll(this, 'activateMarker', 'deactivateMarker');
		var num = this.model.getField('place', 'lat') + this.model.getField('place', 'lng');
		
		if (num in options.markers) {
			this.model.marker = options.markers[num];
		}
		else
		{
			var marker = new google.maps.Marker({
				map: Appetizor.map,
				position: new google.maps.LatLng(
					this.model.getField('place', 'lat'), 
					this.model.getField('place', 'lng')),
			});
			this.model.marker = marker;
			options.markers[num] = marker;
		}
    },
	
	onMarkerHover: function () {
		
	},
	
	onMarkerLeave: function () {
		
	},
	
	activateMarker: function () {
		this.model.marker.setAnimation(google.maps.Animation.BOUNCE);
	},
	
	deactivateMarker: function () {
		this.model.marker.setAnimation(null);
	}
});

Appetizor.backbone.DishListView = Backbone.View.extend({

	events: {
		"mouseenter" : "onDishTileHover",
		"mouseleave" : "onDishTileLeave",
		"click" : "onDishTileClick",
	},

    initialize: function (options) {
		_.bindAll(this);
		this.template = _.template($('#dish-list-item-tmpl').html());
    },

    render: function () {
		$(this.el).html(this.template({ 
			htmlId : this.model.get('pk'), 
			name : this.model.getField('name'),
			slug : this.model.getField('slug'),
			place_slug : this.model.getField('place', 'slug'),
			place_name : this.model.getField('place', 'name'),
		}));
				
		return this;
    },
	
	addMouseEnterListener: function (callback) {			
		this.model.bind("onDishTileHover", callback);
	},
	
	addMouseLeaveListener: function (callback) {			
		this.model.bind("onDishTileLeave", callback);
	},
	
	addClickListener: function (callback) {			
		this.model.bind("onDishTileClick", callback);
	},
	
	onDishTileHover: function () {
		this.model.trigger("onDishTileHover", this.model);
	},
	
	onDishTileLeave: function () {
		this.model.trigger("onDishTileLeave", this.model);
	},
	
	onDishTileClick: function () {
		this.model.trigger("onDishTileClick", this.model);
	},
});


Appetizor.backbone.DishDetailsView = Backbone.View.extend({
	
    initialize: function (options) {
		_.bindAll(this);
		this.template = _.template($('#dish-details-tmpl').html());		
    },

    render: function () {
		$(this.el).html(this.template({ 
			htmlId : this.model.get('pk'), 
			name : this.model.getField('name'),
			slug : this.model.getField('slug'),
			place_slug : this.model.getField('place', 'slug'),
			place_name : this.model.getField('place', 'name'),
			img_src : this.model.getExtra('medium_img_url'),
		}));
			
		return this;
    },
});

jQuery.fn.extend({
	slideToggle: function(isActive, f) {
		var g = f;
		return this.each(function(g) {
			
			return false;
		});
	},
	
	slideHide: function() {
		return this.each(function() {
			var el = $(this);
			el.animate({
				width: 'hide',
				}, 200
			);
		});				
	}		
});

Appetizor.setup = function(dishesJson, options) {
	if (options !== undefined && "showMap" in options && options["showMap"] === true)
	{
		// create map
		var latlng = new google.maps.LatLng(40.7669792, -73.9845695);
		var myOptions = {
			zoom: 13,
			center: latlng,
			mapTypeId: google.maps.MapTypeId.ROADMAP
		};
   
		Appetizor.map = new google.maps.Map($("#map-canvas").get(0), myOptions);
	}
	
	// attach close detail pane handler
	$(".panel-close-btn").click(function () {
		$("#slideout-panel").slideHide();
	});

	// put slideout behind
	$("#left-container").css("z-index", "1002");
	$("#slideout-panel").css("z-index", "1001");
	$("#filter-panel").css("z-index", "9999");

	if (dishesJson) {
		this.dishes = new this.backbone.DishCollection(dishesJson);
		this.mainView = new this.backbone.MainView({ model: this.dishes });		
	}
}

Backbone.Model.prototype.getField = function () {
	var retVal = this.get('fields');
	for ( var i = 0; i < arguments.length; i++ ) {
		retVal = retVal[arguments[i]]
	}
	return retVal;
}

Backbone.Model.prototype.getExtra = function () {
	var retVal = this.get('extras');
	for ( var i = 0; i < arguments.length; i++ ) {
		retVal = retVal[arguments[i]]
	}
	return retVal;
}